package com;

import com.Model.TableData;
import com.Utils.FileUtil;
import com.Utils.Log;
import com.Utils.PdftoPng;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.*;
import java.util.*;

//将所需要的转换为png和html
public class Copyneed {
    public static void main(String[] args) throws IOException, TemplateException {
        TableData tableData = readExcel(new File("C:\\Users\\Administrator\\Desktop\\plant2\\03.Genome_Component\\Gene\\JIN-23_Chl.gff"));
        makeTableHtml(tableData,"C:\\Users\\Administrator\\Desktop\\plant3\\tt.html","C:\\Users\\Administrator\\Desktop\\so\\htmlScript\\plantMitochondria");
    }
    public static Map<String,Object> needMap(String packagepath,String mobanpath,String pppath,String moban,String htmlname) throws IOException, TemplateException {
        System.out.println("--using："+moban+" template--");
        ArrayList<String> check = CheckNeed.check(packagepath, pppath);
        if(check.size()>0){
            Log.printlog(packagepath,false,htmlname,check,moban);
            return null;
        }
        makeneddpackages(packagepath);
        Properties pp = new Properties();
        pp.load(new FileReader(pppath));
        Set<String> strings = pp.stringPropertyNames();
        HashMap<String, Object> result = new HashMap<String,Object>();
        for(String key : strings){
            String property = pp.getProperty(key);
            property = property.replace("/",File.separator);
            property = property.replace("\\",File.separator);
            if(property.contains("*")){
                String warning = property;
                property = removestar(property,packagepath);
                if(property.substring(property.length()-1).equals(File.separator)){
                    System.out.println("warning:" +"no file!!!! "+ warning);
                }
            }
            String s = toPngAndHtml(property, packagepath, mobanpath);
            result.put(key,s);
        }
        return result;
    }
    //获得文件后缀
    public static String houzhui(String ss){
        int i = ss.lastIndexOf(".");
        return ss.substring(i+1);
    }

    public static String toPngAndHtml(String filepath,String packagePath,String moban) throws IOException, TemplateException {
        String sp = File.separator;
        String s1 = packagePath + sp + filepath;
        if(!new File(s1).exists()){System.out.println("warning：No files or folders exist："+s1);}
        String houzhui = houzhui(s1);
        String s2 = packagePath + sp+"res"+sp;
        if(houzhui.equals("png")){
            s2 = s2+filepath;
            new File(s2.substring(0,s2.lastIndexOf(sp))).mkdirs();
            FileUtil.copyFile(s1,s2);
        }
        if(houzhui.equals("pdf")){
            s2 = s2 + filepath;
            s2 = s2 .substring(0,s2.length()-3)+"png";
            new File(s2.substring(0,s2.lastIndexOf(sp))).mkdirs();
            PdftoPng.pdfFileToImage(new File(s1),s2);
        }
        if(houzhui.equals("xls") || houzhui.equals("txt")||houzhui.equals("gff")){
            File file1 = new File(s1);
            String name = file1.getName();
            TableData tableData = readExcel(file1);
            s2 = s2 + filepath.substring(0,filepath.indexOf(sp))+sp+name.substring(0,name.length()-3)+"html";
            makeTableHtml(tableData,s2,moban);
        }
        int i = packagePath.length() + 1;
        return s2.substring(i);
    }

    public static TableData readExcel(File file)  {
        try {
            ArrayList<List<String>> result = new ArrayList<List<String>>();
            BufferedReader bb = new BufferedReader(new FileReader(file));
            String line = null;
            while((line = bb.readLine()) != null){
                String[] split = line.split("\t");
                ArrayList<String> list = new ArrayList<String>();
                for(String a: split){
                    list.add(a);
                }
                result.add(list);
            }
            return getTableData(result);
        } catch (IOException e) {
            System.out.println("--warning :   may be no file "+file.getAbsolutePath());
        }
        return null;
    }

    public static TableData getTableData(List<List<String>> list){
        TableData tableData = new TableData();
        tableData.setTableOneLine(list.get(0));
        list.remove(0);
        tableData.setTableOtherLine(list);
        return tableData;
    }

    public static void makeTableHtml(TableData tableData,String p,String moban) throws IOException, TemplateException {
        // 第一步：创建一个 Configuration 对象，直接 new 一个对象。构造方法的参数就是 freemarker的版本号。
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 第二步：设置模板文件所在的路径。
        configuration.setDirectoryForTemplateLoading(new File(moban));
        // 第三步：设置模板文件使用的字符集。一般就是 utf-8.
        configuration.setDefaultEncoding("UTF-8");
        // 第四步：加载一个模板，创建一个模板对象。
        Template template = null;
        template = configuration.getTemplate("tableTemp.ftl");
        // 第五步：创建一个模板使用的数据集，可以是 pojo 也可以是 map。一般是 Map。
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("table",tableData);

        // 第六步：创建一个 Writer 对象，一般创建一 FileWriter 对象，指定生成的文件名。
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(p)),"utf-8"));
        // 第七步：调用模板对象的 process 方法输出文件。
        template.process(map,writer);
        // 第八步：关闭流
        writer.flush();
        writer.close();
    }

    public static String removestar(String path,String packagepath){

        String result = "";
        String sp = File.separator;
        String s = packagepath+sp+path;
        String[] split = s.split("\\*");
        ArrayList<String> strings = new ArrayList<String>();
        for(String k : split){
            strings.add(k);
            strings.add("*");
        }
        strings.remove(strings.size()-1);
        int size = strings.size();
        for(int a = 0;a < size;a++){
            if(!strings.get(a).equals("*")){
                result = result + strings.get(a);
            }else{
                if(strings.get(a+1).substring(0,1).equals(sp)){
                    File file1 = new File(result);
                    File[] files = file1.listFiles();
                    for(File file : files){
                        if(file.isDirectory()){
                            result = file.getAbsolutePath();
                            break;
                        }
                    }
                }else{
                    String ss = strings.get(a + 1);
                    File[] files = new File(result).listFiles();
                    for(File file : files){
                        if(!file.isDirectory() && file.getName().contains(ss)){
                            result = file.getAbsolutePath();
                            break;
                        }
                    }
                }

            }
        }
        if(!strings.get(strings.size()-1).substring(0,1).equals(sp)){
            int length = strings.get(strings.size() - 1).length();
            result = result.substring(0,result.length()-length);
        }
        result = result.substring(packagepath.length()+1);
        return result;
    }

    public static void makeneddpackages(String packagepath){
        String sp = File.separator;
        new File(packagepath+sp+"res"+sp+"01.RawDataQC").mkdirs();
        new File(packagepath+sp+"res"+sp+"02.Assembly").mkdirs();
        new File(packagepath+sp+"res"+sp+"03.Genome_Component").mkdirs();
        new File(packagepath+sp+"res"+sp+"04.Genome_Annotation").mkdirs();
        new File(packagepath+sp+"res"+sp+"05.Genome_Map").mkdirs();
    }

}
